程式碼分享加小紀錄,如果能幫到你的話就太好了
透過滾動才出現的box,會淡入,當畫面滾動到看不見該box,他就會在看不到的地方悄悄淡出。
如果是資訊滿滿的網站大概會覺得很煩,不過應該還蠻適合好看就好的單一頁面(?
import { useEffect, useState, useRef } from "react";
export default function ScrollingExample() {
const domRef = useRef(null);
const [isVisible, setVisible] = useState(false);
useEffect(() => {
const handleScroll = () => {
if (domRef.current) {
const { top, bottom } = domRef.current.getBoundingClientRect();
const isVisible = top < window.innerHeight && bottom >= 0;
setVisible(isVisible);
}
};
// 初始化時檢查一次
handleScroll();
// 滾動時偵測
window.addEventListener("scroll", handleScroll);
// 清理函數
return () => {
window.removeEventListener("scroll", handleScroll);
};
}, []);
return {
domRef,
fadeInOut: {
transition: "opacity .6s ease-in-out",
opacity: isVisible ? 1 : 0,
},
};
}
// 匯入ScrollingExample
const Container = ({ title }) => {
const { domRef, fadeInOut } = ScrollingExample();
return (
<div
ref={domRef}
style={{
...fadeInOut,
height: "500px",
backgroundColor: "black",
color: "white",
padding: "50px",
marginBottom: "100px",
fontSize: "2em",
}}
>
{title}
</div>
);
}
function ScrollTest() {
return (
<div>
<Container title="box 1" />
<Container title="box 2" />
<Container title="box 3" />
<Container title="box 4" />
<Container title="box 5" />
</div>
);
}
export default ScrollTest;